package com.guofen.service.sjq.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guofen.dao.SjqWaterProcessMapper;
import com.guofen.pojo.SjqWaterProcess;
import com.guofen.pojo.SjqWaterProcessVO;
import com.guofen.service.sjq.SjqWaterProcessService;
import com.guofen.util.DateAndTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SjqWaterProcessServiceImpl implements SjqWaterProcessService {

    @Autowired
    private SjqWaterProcessMapper sjqWaterProcessMapper;

    @Override
    public boolean addForm(String time,double instantaneous_flow,double flow_meter_reading_1,
                           double flow_meter_reading_2, double flow_meter_reading_total,
                           double o_level,String soil_discharging_start_time,
                           String soil_discharging_end_time,double alkali_dosage_A,
                           double alkali_dosage_O, String remarks) {
        //获取当前日期
        String date = DateAndTimeUtil.getDate();
        double reflux_ratio = 4;    //固定为4
        SjqWaterProcess sjqWaterProcess = new SjqWaterProcess();
        //要计算再显示的参数不应该直接插入，所以这里只能插入基础数据
        sjqWaterProcess.setDate(date);
        sjqWaterProcess.setTime(time);
        sjqWaterProcess.setInstantaneousFlow(instantaneous_flow);
        sjqWaterProcess.setFlowMeterReading1(flow_meter_reading_1);
        sjqWaterProcess.setFlowMeterReading2(flow_meter_reading_2);
        sjqWaterProcess.setFlowMeterReadingTotal(flow_meter_reading_total);
        sjqWaterProcess.setoLevel(o_level);
        sjqWaterProcess.setSoilDischargingStartTime(soil_discharging_start_time);
        sjqWaterProcess.setSoilDischargingEndTime(soil_discharging_end_time);
        sjqWaterProcess.setRefluxRatio(reflux_ratio);
        sjqWaterProcess.setAlkaliDosageA(alkali_dosage_A);
        sjqWaterProcess.setAlkaliDosageO(alkali_dosage_O);
        sjqWaterProcess.setRemarks(remarks);

        /**以下数据都是计算出来的数据，非基础数据**/
        //计算排泥量
        double sludgeDischarge = caculateTimeDiffer(soil_discharging_start_time, soil_discharging_end_time)*24*25;
        sjqWaterProcess.setSludgeDischarge(sludgeDischarge);

        // 新加数据时就将WaterYieldDay计算好
        double last_flow_meter_reading_total = sjqWaterProcessMapper.findLast().getFlowMeterReadingTotal();
        sjqWaterProcess.setWaterYieldDay(flow_meter_reading_total - last_flow_meter_reading_total);

        //插入完毕
        int result = sjqWaterProcessMapper.insert(sjqWaterProcess);

        //获取相同日期的其他记录，并更新water_yield_total, total_processing_capacity
        List<SjqWaterProcess> list = sjqWaterProcessMapper.selectAll();
        List<SjqWaterProcess> sameDateList = new ArrayList<>();

        //寻找相同日期
        for(SjqWaterProcess s: list){
            if(s.getDate().equals(date)){
                sameDateList.add(s);
            }
        }

        //统一更新water_yield_total, total_processing_capacity
        double water_yield_total = 0;
        double total_processing_capacity = 0;
        for(SjqWaterProcess s : sameDateList){
            water_yield_total += s.getWaterYieldDay();
            total_processing_capacity += s.getWaterYieldDay()+s.getSludgeDischarge();
        }

        sjqWaterProcess.setWaterYieldTotal(water_yield_total);
        sjqWaterProcess.setTotalProcessingCapacity(total_processing_capacity);
        sjqWaterProcess.setReturnFlow(reflux_ratio * total_processing_capacity);
        for(SjqWaterProcess s : sameDateList){
            s.setWaterYieldTotal(water_yield_total);
            s.setTotalProcessingCapacity(total_processing_capacity);
            s.setReturnFlow(reflux_ratio * total_processing_capacity);
            sjqWaterProcessMapper.updateByPrimaryKeySelective(s);
        }

        if (result == 1)
            return true;
        else
            return false;
    }

    @Override
    public SjqWaterProcess findForm() {
        //获取当前日期
        String date = DateAndTimeUtil.getDate();
        System.out.println("当前日期" + date);
        //获取最新记录
        SjqWaterProcess sjqWaterProcess = sjqWaterProcessMapper.findLast();
        System.out.println("最新记录" + sjqWaterProcessMapper.findLast());
        //获取最新记录日期
        String dateLast =  sjqWaterProcess.getDate();
        System.out.println("最新记录日期" + dateLast);

        if (date.equals(dateLast))
            return sjqWaterProcess;
        else
            return null;
    }

    @Override
    public Map<String, Object> get(int pageSize, int currentPage) {
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(currentPage, pageSize);
        List<SjqWaterProcess> list = sjqWaterProcessMapper.selectAll();
        this.getDiffer(list);
        PageInfo pageRecord = new PageInfo(list);
        long sum = pageRecord.getTotal();
        list = pageRecord.getList();
        map.put("records",list);
        map.put("sum",sum);
        return map;
    }

    @Override
    public Map<String, Object> getByTime(int pageSize, int currentPage, long startTime, long endTime) {
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(currentPage, pageSize);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String startDate = dateFormat.format(new Date(startTime));
        String endDate = dateFormat.format(new Date(endTime));
        List<SjqWaterProcess> list = sjqWaterProcessMapper.selectByDate(startDate, endDate);
        this.getDiffer(list);
        PageInfo pageRecord = new PageInfo(list);
        long sum = pageRecord.getTotal();
        list = pageRecord.getList();
        map.put("records",list);
        map.put("sum",sum);
        return map;
    }

    @Override
    public int delete(int id) {
        return sjqWaterProcessMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int update(SjqWaterProcess record) {
        return sjqWaterProcessMapper.updateByPrimaryKeySelective(record);
    }

    private void getDiffer(List<SjqWaterProcess> list){

        for(SjqWaterProcess sjqWaterProcess:list){

            sjqWaterProcess.setWaterYieldDay(0.00);
            sjqWaterProcess.setWaterYieldTotal(0.00);
            sjqWaterProcess.setSludgeDischarge(0.00);
            sjqWaterProcess.setTotalProcessingCapacity(0.00);
            sjqWaterProcess.setReturnFlow(0.00);
            sjqWaterProcess.setRefluxRatio(4.00);
        }
        for(int i=0; i<list.size(); i++){

            String[] c1 = list.get(i).getSoilDischargingEndTime().split(":");
            String[] c2 = list.get(i).getSoilDischargingStartTime().split(":");
            int b1 = Integer.parseInt(c1[0]);
            int b2 = Integer.parseInt(c1[1]);
            int b3 = Integer.parseInt(c2[0]);
            int b4 = Integer.parseInt(c2[1]);
            //计算出二者的分钟数
            int end = ((b1*60+b2)-(b3*60+b4)+24*60)%(24*60);

            list.get(i).setSludgeDischarge(Double.valueOf(end/60*25));
            System.out.println("排泥量："+list.get(i).getSludgeDischarge());
            if(i==0){
                continue;
            }else{
                list.get(i).setWaterYieldDay(list.get(i).getFlowMeterReadingTotal()-list.get(i-1).getFlowMeterReadingTotal());
            }
        }

        int i = 0;
        int j = i;
        while(j<list.size()){
            System.out.println(list.get(i).getId());
            if(list.get(i).getDate().equals(list.get(j).getDate())){
                System.out.println("aaaa:"+list.get(i).getWaterYieldTotal());
                list.get(i).setWaterYieldTotal(list.get(i).getWaterYieldTotal()
                        +list.get(j).getWaterYieldDay());
                System.out.println("id:"+list.get(i).getId());
                j++;
                System.out.println("上循环i:"+i);
                System.out.println("上循环j:"+j);
            }else{
                i=j;
            }
        }
        i=0;
        j=0;
        list.get(0).setTotalProcessingCapacity(list.get(i).getWaterYieldTotal());
        while(j<list.size()){

            if(list.get(i).getDate().equals(list.get(j).getDate())){
                list.get(i).setTotalProcessingCapacity(list.get(i).getTotalProcessingCapacity()
                +list.get(i).getSludgeDischarge());
                list.get(i).setReturnFlow(list.get(i).getSludgeDischarge()*list.get(i).getRefluxRatio());
                j++;
            }else{
                i=j;
                list.get(i).setTotalProcessingCapacity(list.get(i).getWaterYieldTotal());
            }
        }
    }

    //更新数据库
    @Override
    public void updateAll() {
        List<SjqWaterProcess> list = sjqWaterProcessMapper.selectAll();
        int size = list.size();
        //更新water_yield_day, sludge_discharge, water_yield_total,total_processing_capacity, return_flow
        for (int i = 1; i <= size - 1; i++) {
            SjqWaterProcess current = list.get(i);
            SjqWaterProcess upper = list.get(i - 1);
            //water_yield_day
            current.setWaterYieldDay(current.getFlowMeterReadingTotal() - upper.getFlowMeterReadingTotal());
            //sludge_discharge
            current.setSludgeDischarge(caculateTimeDiffer(current.getSoilDischargingStartTime(),current.getSoilDischargingEndTime())*24*25);
            sjqWaterProcessMapper.updateByPrimaryKeySelective(current);
        }
        list.get(0).setWaterYieldDay(0.0);
        list.get(0).setSludgeDischarge(caculateTimeDiffer(list.get(0).getSoilDischargingStartTime(),list.get(0).getSoilDischargingEndTime())*24*25);
        sjqWaterProcessMapper.updateByPrimaryKeySelective(list.get(0));

        //更新water_yield_total

        //按日期进行分组
        Map<String, List<SjqWaterProcess>> sjqWaterProcessMap = new HashMap<>();
        for (SjqWaterProcess sjqWaterProcess : list) {
            List<SjqWaterProcess> tempList = sjqWaterProcessMap.get(sjqWaterProcess.getDate());
            /*如果取不到数据,那么直接new一个空的ArrayList**/
            if (tempList == null) {
                tempList = new ArrayList<>();
                tempList.add(sjqWaterProcess);
                sjqWaterProcessMap.put(sjqWaterProcess.getDate(), tempList);
            } else {
                tempList.add(sjqWaterProcess);
            }
        }

        //相同日期的算总和
        for(String date : sjqWaterProcessMap.keySet()){
            System.out.println(sjqWaterProcessMap.get(date));
            List<SjqWaterProcess> tempList = sjqWaterProcessMap.get(date);
            double water_yield_total = 0;
            double total_processing_capacity = 0;
            // water_yield_total
            for(SjqWaterProcess sjqWaterProcess : tempList){
                water_yield_total += sjqWaterProcess.getWaterYieldDay();
                total_processing_capacity += sjqWaterProcess.getWaterYieldDay() + sjqWaterProcess.getSludgeDischarge();
            }
            //更新total
            for(SjqWaterProcess sjqWaterProcess : tempList){
                sjqWaterProcess.setRefluxRatio(4.0);
                sjqWaterProcess.setWaterYieldTotal(water_yield_total);
                sjqWaterProcess.setTotalProcessingCapacity(total_processing_capacity);
                sjqWaterProcess.setReturnFlow(total_processing_capacity * sjqWaterProcess.getRefluxRatio());
                sjqWaterProcessMapper.updateByPrimaryKeySelective(sjqWaterProcess);
            }
        }


    }

    private static double caculateTimeDiffer(String startTime, String endTime){
        String[] list1 = startTime.split(":");
        String[] list2 = endTime.split(":");
        int hour = Integer.parseInt(list2[0]) - Integer.parseInt(list1[0]);
        int min = Integer.parseInt(list2[1]) - Integer.parseInt(list1[1]);
        double result = hour + min/60.0;
        return result;
    }

}
